<template>
  <aside class="note-list">
    <!-- 头部添加笔记按钮 -->
    <div class="toolbar">
      <button @click="onAddNote" :title="addButtonTitle">
        <i class="iconfont iconnewfile"></i> 添加笔记
      </button>
    </div>
    <!-- 笔记列表 -->
    <div class="notes">
      <div
        class="note"
        :title="note.filePath || note.title"
        :class="{ selected: note === selectedNote }"
        @click="onSelectNote(note)"
        v-for="note of sortedNotes"
        :key="note.id"
      >
        <i class="right iconfont iconstar" v-if="note.favorite"></i>
        {{ note.title }}
      </div>
    </div>
  </aside>
</template>

<script lang="ts">
import { Component, Prop, Vue, Emit } from 'vue-property-decorator'
import Note from '@/Note'
import Notes from '@/Notes'

@Component
export default class NoteList extends Vue {
  /** 所有笔记 */
  @Prop() readonly notes!: Notes

  /** 当前选中的笔记 */
  @Prop() readonly selectedNote!: Note

  /**
   * “添加”按钮的 title 文本
   */
  get addButtonTitle(): string {
    return `已有 ${this.notes.length} 篇笔记`
  }

  /**
   * 排序后的所有笔记
   */
  get sortedNotes(): Note[] {
    return this.notes.notes
  }

  /**
   * 创建一个新笔记
   * @listens
   * @fires NoteList#add
   */
  @Emit('add')
  onAddNote() {}

  /**
   * 选中一个指定的笔记
   * @listens
   * @param {Note} note 选中的笔记
   * @fires NoteList#select
   */
  @Emit('select')
  onSelectNote(note: Note) {
    /**
     * @event NoteList#select
     * @param {Note} 选中的笔记
     */
  }

  mounted() {
    window.addEventListener('selectstart', function(e) {
      const target = e.target as HTMLElement
      if (target) {
        const elName = target.localName
        if (elName != 'input' && elName != 'textarea') {
          e.preventDefault()
        }
      }
    })
  }
}
</script>

<style lang="scss" scoped>
$line-height: 24px; // 列表文字的行高

.note-list {
  background: #f8f8f8;
  padding: 2px;

  .toolbar {
    margin-bottom: 2px;
    button {
      width: 100%;
    }
  }

  // 列表
  .notes {
    flex: auto 1 1;
    overflow: auto;
    .note {
      padding: 4px 8px;
      margin-bottom: 2px;
      cursor: pointer;
      font-size: 14px;
      line-height: $line-height;
      border-radius: $border-radius;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      &:hover {
        background: $light-color;
      }
      &.selected {
        @include primary;
      }
      .right {
        display: block;
        margin: 0;
        padding: 0;
        float: right;
        font-size: 90%;
        line-height: $line-height;
      }
    }
  }
}
</style>
